//
//  OCASegmentedControl.m
//  OCAFramework
//
//  Created by Wu Yanna on 12-3-6.
//  Copyright (c) 2012年 DP. All rights reserved.
//

#import "OCASegmentedControl.h"
@interface OCASegmentedControl (Private)
- (void)defaultInitialization;
@end
@implementation OCASegmentedControl

@synthesize selectedSegmentIndex;
@synthesize numberOfSegments;
@synthesize segDelegate;
@synthesize enabled;
@synthesize maxNumberOfSegments;
//@synthesize contentWidth;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        [self defaultInitialization];
    }
    return self;
}

- (void)dealloc {
    [_buttonArray release];
    [super dealloc];
}

- (void)awakeFromNib {
    [self defaultInitialization];
}

- (void)defaultInitialization {
    self.pagingEnabled = NO;
    self.directionalLockEnabled = YES;
    self.showsVerticalScrollIndicator = NO;
    self.showsHorizontalScrollIndicator = NO;
    self.maxNumberOfSegments = 4;
}

- (void)layoutSubviews {
    
    NSInteger buttonCount;
    
    if ([_buttonArray count] > self.maxNumberOfSegments) {
        buttonCount = self.maxNumberOfSegments;
        self.scrollEnabled = YES;
        
    } else {
        buttonCount = [_buttonArray count];
        self.scrollEnabled = NO;
    }
    
    float segmentWidth = self.frame.size.width / buttonCount;
    float segmentStartX = 0;
    for (int i = 0; i < [_buttonArray count]; i++) {
        UIButton *button = [_buttonArray objectAtIndex:i];
        button.frame = CGRectMake(segmentStartX, 0, segmentWidth, self.frame.size.height);
        segmentStartX += segmentWidth;
    }
    
    // 不设置contentSize无法滑动！！
    if (self.scrollEnabled) {
        [self setContentSize:CGSizeMake((segmentWidth * [_buttonArray count]), self.frame.size.height)];
    }
}

- (void)setEnabled:(BOOL)aEnabled {
    for (int i = 0; i < [_buttonArray count]; i++) {
        UIButton *button = [_buttonArray objectAtIndex:i];
        [button setEnabled:aEnabled];
    }
}

- (void)setNumberOfSegments:(NSUInteger)aNumberOfSegments {
    [_buttonArray release];
    numberOfSegments = aNumberOfSegments;
    _buttonArray = [[NSMutableArray arrayWithCapacity:numberOfSegments]retain];
    for (int i=0; i <numberOfSegments; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        if (i == 0) {
            button.selected = YES;
            [button setBackgroundImage:[[UIImage imageNamed:@"segmentCtrlBg_Left.png"]stretchableImageWithLeftCapWidth:2 topCapHeight:0]  forState:UIControlStateNormal];
            [button setBackgroundImage:[[UIImage imageNamed:@"segmentCtrlBg_Left_s.png"]stretchableImageWithLeftCapWidth:2 topCapHeight:0] forState:UIControlStateHighlighted];
            [button setBackgroundImage:[[UIImage imageNamed:@"segmentCtrlBg_Left_s.png"]stretchableImageWithLeftCapWidth:2 topCapHeight:0] forState:UIControlStateSelected];
        } else{
            if (i == numberOfSegments - 1) {
                [button setBackgroundImage:[[UIImage imageNamed:@"filterbar.png"]stretchableImageWithLeftCapWidth:0 topCapHeight:0] forState:UIControlStateNormal];
                [button setBackgroundImage:[[UIImage imageNamed:@"filterbar_selected.png"] stretchableImageWithLeftCapWidth:0 topCapHeight:0] forState:UIControlStateHighlighted];
                [button setBackgroundImage:[[UIImage imageNamed:@"filterbar_selected.png"] stretchableImageWithLeftCapWidth:0 topCapHeight:0] forState:UIControlStateSelected];
            } else {
                [button setBackgroundImage:[[UIImage imageNamed:@"segmentCtrlBg_Left.png"]stretchableImageWithLeftCapWidth:2 topCapHeight:0] forState:UIControlStateNormal];
                [button setBackgroundImage:[[UIImage imageNamed:@"segmentCtrlBg_Left_s.png"]stretchableImageWithLeftCapWidth:2 topCapHeight:0] forState:UIControlStateHighlighted];
                [button setBackgroundImage:[[UIImage imageNamed:@"segmentCtrlBg_Left_s.png"]stretchableImageWithLeftCapWidth:2 topCapHeight:0] forState:UIControlStateSelected];
            }
            button.selected = NO;
        }
        
        //778bad
        [button titleLabel].font = [UIFont boldSystemFontOfSize:16];
        [button setTitleColor:[UIColor colorWithRed:0x77/255.f green:0x8b/255.f blue:0xad/255.f alpha:1] forState:UIControlStateNormal];
        [button setTag:i];
        [button addTarget:self action:@selector(touchAction:) forControlEvents:UIControlEventAllTouchEvents];
        [button addTarget:self action:@selector(action:) forControlEvents:UIControlEventTouchDown];
        
        [_buttonArray addObject:button];
        [self addSubview:button];
    }
    //self.selectedSegmentIndex = 0;
    //[self layoutIfNeeded];
}

- (void)setSelectedSegmentIndex:(NSInteger)aSelectedSegmentIndex {
	if (selectedSegmentIndex<_buttonArray.count) {
		UIButton *preButton = [_buttonArray objectAtIndex:selectedSegmentIndex];
		preButton.selected = NO;
	}
    
    selectedSegmentIndex = aSelectedSegmentIndex;
	
	if (selectedSegmentIndex<_buttonArray.count) {
		UIButton *currentButton = [_buttonArray objectAtIndex:selectedSegmentIndex];
		currentButton.selected = YES;
        
        if (self.scrollEnabled) {
            [self scrollRectToVisible:currentButton.frame animated:YES];
        }
	}
    
    
    
    if ([segDelegate respondsToSelector:@selector(valueChanged:selectedSegmentIndex:)]) {
        [segDelegate valueChanged:self selectedSegmentIndex:selectedSegmentIndex];
    }
}

- (void)setBackgroundImage:(UIImage *)backgroundImage forState:(OCASegmentedControlState)state AtPosition:(OCASegmentedControlPosition)position {
    if (position == OCASegmentedControlLeft) {
        [self setBackgroundImage:backgroundImage forState:state AtIndex:0];  
    } else if (position == OCASegmentedControlRight) {
        [self setBackgroundImage:backgroundImage forState:state AtIndex:numberOfSegments - 1];
    } else if (position == OCASegmentedControlMiddle) {
        for (int i = 1; i < numberOfSegments - 1; i++) {
            [self setBackgroundImage:backgroundImage forState:state AtIndex:i];
        }
    } else {
        for (int i = 0; i < numberOfSegments; i++) {
            [self setBackgroundImage:backgroundImage forState:state AtIndex:i];
        }
    }
}

- (void)setBackgroundImage:(UIImage *)backgroundImage forState:(OCASegmentedControlState)state AtIndex:(NSInteger)index {
    if (index >= numberOfSegments) {
        NSLog(@"ERROR: Segment index:%d out of bounds:[0 - %d]", index, numberOfSegments-1);
        return;
    }
    
    UIButton *button = [_buttonArray objectAtIndex:index];
    if (state == OCASegmentedControlStateNormal) {
        [button setBackgroundImage:backgroundImage forState:UIControlStateNormal];
    }else if (state == OCASegmentedControlStateSelected) {
        [button setBackgroundImage:backgroundImage forState:UIControlStateHighlighted];
        [button setBackgroundImage:backgroundImage forState:UIControlStateSelected];
    }
}

- (void)setTitle:(NSString *)title forSegmentAtIndex:(NSUInteger)segment {
    UIButton *button = [_buttonArray objectAtIndex:segment];
    [button setTitle:title forState:UIControlStateNormal];
}

- (void)touchAction:(id)sender {
    UIButton *button = (UIButton *)sender;
    button.selected = YES;
    button.highlighted = NO;
}
- (void)action:(id)sender {
    UIButton *button = (UIButton *)sender;
    if (button.tag == selectedSegmentIndex) {
        return;
    }
    [self setSelectedSegmentIndex:button.tag];
}

- (UIButton*) buttonForIndex:(int)index
{
    if(_buttonArray!=nil && _buttonArray.count>index)
    {
        return [_buttonArray objectAtIndex:index];
    }
    return nil;
}

@end
